package netty

import io.netty.bootstrap.ServerBootstrap
import io.netty.channel.ChannelOption
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.nio.NioServerSocketChannel


class NettyServer {

    @Throws(Exception::class)
    fun bind(port: Int) {

        val bossGroup = NioEventLoopGroup() //bossGroup就是parentGroup，是负责处理TCP/IP连接的
        val workerGroup = NioEventLoopGroup() //workerGroup就是childGroup,是负责处理Channel(通道)的I/O事件

        val sb = ServerBootstrap()
        sb.group(bossGroup, workerGroup)
            .channel(NioServerSocketChannel::class.java)
            .option(ChannelOption.SO_BACKLOG, 1000000) //初始化服务端可连接队列,指定了队列的大小128
            .childOption(ChannelOption.TCP_NODELAY, true)//立即模式
//            .childOption(ChannelOption.SO_KEEPALIVE, true) //保持长连接
            .childHandler(NettyChannelInitializer())
        //绑定监听端口，调用sync同步阻塞方法等待绑定操作完
        val future = sb.bind(port).sync()

        if (future.isSuccess) {
            println("服务端启动成功")
        } else {
            println("服务端启动失败")
            future.cause().printStackTrace()
            bossGroup.shutdownGracefully() //关闭线程组
            workerGroup.shutdownGracefully()
        }

        //成功绑定到端口之后,给channel增加一个 管道关闭的监听器并同步阻塞,直到channel关闭,线程才会往下执行,结束进程。
        future.channel().closeFuture().sync()

    }

}